<template>
  <div class="login">
    <div class="container w1200 disf fdc alc jcc">
      <div class="login-box">
        <div class="login-img">
          <img src="@/assets/images/login_img_03.png" alt="" />
        </div>
        <div class="login-form">
          <div class="sj"></div>
          <div class="content">
            <div class="account-log" v-show="loginStyle === 'account'">
              <div class="t ls">登 陆</div>
              <div class="con-form">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
                  <el-form-item prop="nickname">
                    <el-input type="input" v-model="ruleForm.nickname" autocomplete="off" placeholder="用户名">
                      <i slot="prefix" class="el-input__icon el-icon-user"></i></el-input>
                  </el-form-item>
                  <el-form-item prop="pass">
                    <el-input type="password" v-model="ruleForm.pass" autocomplete="off" placeholder="密码">
                      <i slot="prefix" class="el-input__icon el-icon-lock"></i></el-input>
                  </el-form-item>
                  <el-form-item prop="code">
                    <div style="display: flex; justify-content: space-between">
                      <el-input v-model="ruleForm.code" autocomplete="off" placeholder="验证码"></el-input>
                      <div class="vercode-mask">
                        <img v-show="imgShow" :src="vercodeImgSrc" @click="refVercode()" />
                        <div class="vercode-mask" v-show="isOverdue" @click="refVercode()">
                          已过期 请刷新
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                  <el-form-item>
                    <el-button style="width: 100%; background-color: #5288e8" type="primary"
                      @click="submitForm('ruleForm')">登录</el-button>
                    <!-- <el-button @click="register()">注册</el-button> -->
                  </el-form-item>
                </el-form>
              </div>
              <div class="other-login">第三方登录方式</div>
              <div class="other-login-style">
                <div class="item" @click="loginHandle('wechat')">
                  <img src="@/assets/images/login_style_icon_10.jpg" alt="" />
                </div>
                <!-- <div class="item" @click="loginHandle('phone')">
                  <img src="@/assets/images/login_style_icon_07.jpg" alt="" />
                </div> -->
              </div>

              <div class="forgetPsw">忘记密码？</div>
            </div>
            <div class="phone-log" v-show="loginStyle === 'phone'">
              <div class="t">手机号登录</div>
              <div class="con-form">
                <el-form :model="rulePhoneForm" :rules="phoneRules" ref="rulePhoneForm">
                  <el-form-item prop="phone">
                    <el-input type="input" v-model="rulePhoneForm.phone" autocomplete="off" placeholder="手机号">
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="code">
                    <div style="display: flex; justify-content: space-between">
                      <el-input v-model="rulePhoneForm.code" autocomplete="off" placeholder="验证码"></el-input>
                      <div class="vercode-mask">
                        <el-button style="width: 100%; background-color: #5288e8" type="primary"
                          @click="sendCode">发送验证码</el-button>
                      </div>
                    </div>
                  </el-form-item>
                  <el-button style="width: 100%; background-color: #5288e8" type="primary"
                    @click="submitPhoneForm('rulePhoneForm')">登录</el-button>
                </el-form>
              </div>
              <div class="t2" @click="loginHandle('account')">
                &lt; 返回账号密码
              </div>
            </div>
            <div class="wechat-log" v-show="loginStyle === 'wechat'">
              <div class="t">微信扫码登录</div>
              <div class="qc-code">
                <div class="code">
                  <img v-if="!isErrorGet" draggable="false" class="auth-code-img" :src="qrUrl" style="width: 100%" />
                  <div v-if="isErrorGet" @click="getQrCode" class="error-get">
                    <div>二维码获取失败</div>
                    <div>刷新以重新获取</div>
                  </div>
                </div>
              </div>
              <div class="t2" @click="loginHandle('account')">
                &lt; 返回账号密码
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="notice disf alc">
        <div class="disf alc">
          <img src="@/assets/images/notice_03.png" alt="" style="width: 30px" />
          <span class="t1">服务上下架通知</span>
        </div>
        <div class="t2" v-for="(item, index) in tableStringArray" :key="index">
          <template v-if="index < 1">
            {{ item }}
          </template>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { v4 as uuidv4 } from "uuid";
import storage from "store";
import appConfig from "@/config/appConfig";
import apiService from "@/api/apiService";
import Vue from "vue";
import { getCurrentUser } from "@/utils";

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Login",
  data() {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("验证码不能为空"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (value.length > 12) {
        callback(new Error("用户名长度不能超过12"));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    var validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    var checkCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else {
        callback();
      }
    };
    return {
      loginStyle: "account",
      vercodeImgSrc: "", // 验证码图片
      vercodeToken: "", // 验证码验证token
      isOverdue: false,
      imgShow: false,
      qrUrl: "",
      key: "",
      scene_str: "",
      qrCodeDataURL: "",
      tem_poll: "",
      isErrorGet: false,
      services: [], // 存储服务上下架列表
      ruleForm: {
        nickname: "",
        pass: "",
        code: "",
      },
      rulePhoneForm: {
        phone: "",
        code: "",
      },
      tableStringArray: [],
      rules: {
        nickname: [{ validator: validatePass, trigger: "blur" }],
        pass: [{ validator: validatePass2, trigger: "blur" }],
        code: [{ validator: checkAge, trigger: "blur" }],
      },
      phoneRules: {
        phone: [{ validator: validatePhone, trigger: "blur" }],
        code: [{ validator: checkCode, trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.refVercode();
    this.$nextTick(() => {
      this.generateLoginImg();
      this.tem_poll = setInterval(this.loginPoll, 5000);
      this.fetchServices(); // 获取服务列表
    });
  },
  destroyed() {
    clearInterval(this.tem_poll);
  },
  methods: {
    formatCreateTime(createTime) {
      // 将字符串转换为Date对象
      const date = new Date(createTime);

      // 使用toISOString()方法将Date对象转换为ISO字符串，然后分割
      const [datePart, timePart] = date.toISOString().split("T");

      // 移除时间部分的毫秒，并添加秒
      const formattedTime = timePart.slice(0, 8) + "00";

      // 将日期部分和格式化后的时间部分组合起来
      return `${datePart} ${formattedTime}`;
    },
    generateTableString() {
      this.tableStringArray = this.services.map((service) => {
        const formatCreateTime = this.formatCreateTime(service.createTime);
        return `${service.parent}服务${service.serviceName}编号为: ${service.serviceId
          }在${formatCreateTime}${service.type === 0 ? "上架" : "下架"}`;
      });
      console.log(this.tableStringArray);
    },
    generateLoginImg() {
      this.scene_str = uuidv4();
      // apiService.get('/generatePcQrloginUrl?scene_str=' + this.scene_str).then(res => {
      //   this.qrUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + res.ticket;
      //   this.isImageUrlValid(this.qrUrl).then(() => {
      //     this.isErrorGet = false;
      //   }).catch(() => {
      //     this.isErrorGet = true;
      //   });
      // });
      apiService.get("/pcLoginUrl?scene_str=" + this.scene_str).then((res) => {
        this.qrUrl = res.data.imgUrl;
        this.key = res.data.key;
      });
    },
    fetchServices() {
      apiService
        .get("/service/log")
        .then((response) => {
          this.services = response.data;
          this.generateTableString();
        })
        .catch((error) => {
          console.error("Error fetching services:", error);
        });
    },
    isImageUrlValid(url) {
      return new Promise((resolve, reject) => {
        const image = new Image();
        image.onload = () => resolve(true);
        image.onerror = () => reject(new Error("Invalid image URL"));
        image.src = url;
      });
    },
    getQrCode() {
      this.generateLoginImg();
    },
    loginPoll() {
      apiService.post("/pcQrlogin?scene_str=" + this.key).then((res) => {
        if (res.code === 0) {
          clearInterval(this.tem_poll);
          this.$notify({
            title: "登录成功",
            type: "success",
            duration: 1,
          });
          storage.set(
            appConfig.ACCESS_TOKEN_NAME,
            res.data,
            7 * 24 * 60 * 60 * 1000
          );
          getCurrentUser();
          this.$store.dispatch("getCurrentUserInfo");
          apiService.get("/currentUserInfo").then((res) => {
            if (res.code === 0) {
              storage.set(appConfig.APP_USER, res.data);
              this.$store.state.id = res.data.id;
              this.$store.state.roleName = res.data.roleName;
              this.$store.state.point = res.data.pointsBalance;
              const path = storage.get(appConfig.LAST_ROUTER);
              if (path) {
                this.$router.push({ path: path });
                storage.remove(appConfig.LAST_ROUTER);
              } else {
                this.$router.push({ name: "home" });
              }
            } else {
              storage.set(appConfig.ACCESS_TOKEN_NAME, null);
            }
          });
        }
      });
    },
    refVercode() {
      const that = this;
      apiService.get("/code").then((res) => {
        that.vercodeImgSrc = res.data.imageBase64Data;
        that.vercodeToken = res.data.vercodeToken;
        this.imgShow = true;
        this.isOverdue = false;
        if (this.timer) clearInterval(this.timer);
        this.timer = setInterval(() => {
          res.data.expireTime--;
          if (res.data.expireTime <= 0) {
            that.isOverdue = true;
            this.imgShow = false;
            clearInterval(this.timer);
          }
        }, 1000);
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let request = {
            nickName: this.ruleForm.nickname,
            pass: this.ruleForm.pass,
            code: this.ruleForm.code,
            codeToken: this.vercodeToken,
          };
          apiService.post("/login", request).then((res) => {
            if (res.code === 0) {
              storage.set(
                appConfig.ACCESS_TOKEN_NAME,
                res.data,
                7 * 24 * 60 * 60 * 1000
              );

              apiService.get("/currentUserInfo").then((res) => {
                if (res.code === 0) {
                  storage.set(appConfig.APP_USER, res.data);
                  this.$store.commit("setUserInfo", res.data);
                  this.$store.state.id = res.data.id;
                  this.$store.state.roleName = res.data.roleName;
                  this.$store.state.point = res.data.pointsBalance;
                  this.$router.push({ name: "home" });
                  this.$store.dispatch("getCurrentUserInfo");
                } else {
                  storage.set(appConfig.ACCESS_TOKEN_NAME, null);
                }
              });
            } else {
              Vue.prototype.$message.error(res.msg);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    submitPhoneForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          return;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    sendCode() {
      this.$refs.rulePhoneForm.validateField(["phone"], (error) => {
        if (error) {
          console.log("校验失败:", error);
        } else {
          console.log("校验通过");
        }
      });
    },
    register() {
      this.$router.push({ path: "/register" });
    },
    loginHandle(type) {
      this.loginStyle = type;
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.$refs.rulePhoneForm.resetFields();
        this.$refs.ruleForm.clearValidate();
        this.$refs.rulePhoneForm.clearValidate();
      });
    },
  },
  computed: {},
};
</script>
<style lang="scss" scoped>
.login {
  height: 100vh;
  width: 100%;
  background-image: url("@/assets/images/login-bg.jpg");
  background-repeat: no-repeat;
  background-size: 100% 100%;

  .container {
    height: 100%;
    box-sizing: border-box;

    .login-box {
      height: 560px;
      background-color: rgba(174, 203, 248, 0.67);
      width: 100%;
      border-radius: 10px;
      position: relative;

      .login-img {
        width: 50%;
        height: 100%;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;

        img {
          height: 80%;
        }
      }

      .login-form {
        width: 567px;
        height: calc(100% + 60px);
        position: absolute;
        right: 30px;
        top: -30px;
        z-index: 2;

        .sj {
          position: absolute;
          left: -50px;
          top: 0;
          border-bottom: 30px solid #afb1b7;
          border-left: 50px solid transparent;
          border-right: 50px solid transparent;
          z-index: -10;
        }

        .content {
          background-color: #fff;
          border-radius: 0 10px 10px 10px;
          position: relative;
          z-index: 1;
          width: 100%;
          height: 100%;
          background-image: url("@/assets/images/light_03.jpg");
          background-repeat: no-repeat;
          background-position: 98% 0;
          padding-top: 40px;
          text-align: center;

          .t {
            color: #5288e8;
            font-size: 30px;
            text-align: center;

            &.ls {
              letter-spacing: 20px;
            }
          }

          .t2 {
            color: #b0b2b7;
            font-size: 16px;
            cursor: pointer;
            display: inline-block;
            margin-top: 30px;
          }

          .account-log {
            padding: 0 80px;
            position: relative;
            height: 100%;

            .con-form {
              padding-top: 65px;

              .vercode-mask {
                width: 160px;
                flex-shrink: 0;
                height: 40px;
                margin-left: 10px;
                cursor: pointer;
                color: #5288e8;
              }
            }

            .other-login {
              margin-top: 40px;
              text-align: center;
              color: #b0b2b7;
              position: relative;

              &:after {
                content: "";
                height: 1px;
                width: 100px;
                background-color: #b0b2b7;
                position: absolute;
                left: 0;
                top: 50%;
              }

              &:before {
                content: "";
                height: 1px;
                width: 100px;
                background-color: #b0b2b7;
                position: absolute;
                right: 0;
                top: 50%;
              }
            }

            .other-login-style {
              display: flex;
              align-items: center;
              justify-content: center;
              padding-top: 20px;

              .item {
                width: 42px;
                height: 42px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: pointer;

                &:nth-child(1) {
                  background-color: #24c891;
                }

                &:nth-child(2) {
                  background-color: #71d6ed;
                  margin-left: 35px;
                }
              }
            }

            .forgetPsw {
              cursor: pointer;
              position: absolute;
              right: 10px;
              bottom: 30px;
              font-size: 16px;
              color: #b0b2b7;
            }
          }

          .phone-log {
            padding: 0 80px;
            position: relative;
            height: 100%;

            .con-form {
              padding-top: 65px;

              .vercode-mask {
                width: 160px;
                flex-shrink: 0;
                height: 40px;
                margin-left: 10px;
                cursor: pointer;
                color: #5288e8;
              }
            }
          }

          .wechat-log {
            .qc-code {
              display: flex;
              align-items: center;
              justify-content: center;
              padding-top: 70px;

              .code {
                border: 1px solid #999;
                width: 300px;
                height: 300px;
                border-radius: 20px;
                overflow: hidden;

                .error-get {
                  width: 100%;
                  height: 100%;
                  display: flex;
                  flex-direction: column;
                  color: #999;
                }
              }
            }
          }
        }
      }
    }

    .notice {
      margin-top: 60px;
      padding: 20px;
      background-color: #fff;
      border-radius: 10px;
      width: 100%;
      color: #666;

      .t1 {
        font-size: 20px;
        padding-left: 20px;
      }

      .t2 {
        font-size: 14px;
        padding-left: 40px;
      }
    }
  }
}
</style>
